package com.woniuxy.service.impl;

import com.woniuxy.dto.ProductDto;
import com.woniuxy.service.CartService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 曾令忠
 * @Description: 操作redis实现购物车的业务
 * @Date: 2020/7/3 0003-下午 2:31
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    //购物车属性
    private Map<String,Object> mapCart = new HashMap<>();
    @Override
    public int add(ProductDto productDto) {
        //得到当前账号信息
        String uname  = (String) SecurityUtils.getSubject().getSession().getAttribute("user");
    //{"uname":mapCart} mapCart:{pid,detailMap} detailMap:{type,num}

        //获取购物车信息
        Map<Object,Object> data = redisTemplate.opsForHash().entries(uname);

        //判断购物车是否为空
        if(data==null){
            Map<Object,Object> detailMap = new HashMap<>();
            detailMap.put(productDto.getType(),productDto.getNum());
            //放入属性
            mapCart.put(productDto.getPid()+"",detailMap);

            //放入redis
            redisTemplate.opsForHash().putAll(uname,mapCart);
            return 200;
        }
    //data不为null，看是否有当前pid的数据
        if (data.containsKey(productDto.getPid())) {
            //获取数据
            Map<Object,Object> detailMap = (Map<Object,Object>)data.get(productDto.getPid());
            int num = productDto.getNum();
            if(detailMap.containsKey(productDto.getType())){
                num += (Integer)detailMap.get(productDto.getType());
            }
            detailMap.put(productDto.getType(),num);
            redisTemplate.opsForHash().putAll(uname,data);


        }else{
            
        }
        //没有添加过
        Map<Object,Object> detailMap = new HashMap<>();
        detailMap.put(productDto.getType(),productDto.getNum());
        //放入redis
        redisTemplate.opsForHash().putAll(uname,data);
        return 202;
    }

    @Override
    public List<ProductDto> allProduct() {
        String uname  = (String) SecurityUtils.getSubject().getSession().getAttribute("user");
        Map<Object,Object> data = redisTemplate.opsForHash().entries(uname);

        return null;
    }
}
